<script lang="ts" setup>
import { get, post, message, loadFile } from '@/utils'
import Editor from '@/components/Editor/index.vue'
import isEmpty from 'lodash/isEmpty'
import cloneDeep from 'lodash/cloneDeep'
import { FormInstance, TableColumnData } from '@arco-design/web-vue'
interface Transport {
  cityArr: any[] | string
  continuousFee: number
  continuousPiece: number
  firstFee: number
  firstPiece: number
}
const props = defineProps<{
  show: boolean
  id: number | string
}>()
const emit = defineEmits(['update:show', 'reset', 'confirm'])
const formRef = ref() as Ref<FormInstance>
const detail = reactive({
  name: '',
  chargeType: 0,
  isFree: 0,
  isFreeCondition: 0,
  transportFeeList: [],
})
/**获取省市区树 */

const tree = ref<any[]>([])
const getTree = () => {
  get({ url: '/server-shop/sys-seller/region/tree' }, ({ data }) => {
    tree.value = data
  })
}
getTree()
const submit = done => {
  formRef.value.validate(err => {
    const list = cloneDeep(listData.value)
    for (let i = 0; i < list.length; i++) {
      list[i].cityArr = toArrStr(list[i].cityArr)
    }
    console.log(list)

    const query = Object.assign(detail, {
      // transportFeeList: detail.isFree == 0 ? list : [],
      transportFeeList: list,
    })
    console.log('🚀 ~ file: TransportModal.vue:34 ~ formRef.value.validate ~ query:', query)
    if (!err) {
      post(
        { url: '/server-shop/sys-seller/transport/submit', data: query },
        ({ code, msg }) => {
          message({
            type: code == 200 ? 'success' : 'error',
            content: msg,
          })
          emit('update:show', false)
          emit('confirm')
          done(true)
        },
        () => done(false)
      )
    } else done(false)
  })
}
const getInfo = () => {
  get({ url: '/server-shop/sys-seller/transport/info', data: { id: props.id } }, ({ data }) => {
    Object.assign(detail, data)
    for (let i = 0; i < data.transportFeeList.length; i++) {
      const transportFee = data.transportFeeList[i]

      if (transportFee.cityArr.length > 0) {
        data.transportFeeList[i].cityArr = eval(transportFee.cityArr)
      }
    }
    listData.value = data.transportFeeList
    console.log('🚀 ~ get ~ listData:', listData.value[0].cityArr)
  })
}
/**处理table自定义数据 */
const listData = ref<Transport[]>([])
const addArea = (first = false) => {
  listData.value.push({
    cityArr: first ? '' : [],
    continuousFee: 1,
    continuousPiece: 0,
    firstFee: 1,
    firstPiece: 0,
  })
}
onMounted(() => {
  if (props.id) getInfo()
  else {
    addArea(true)
  }
})
const isDisabled = computed(() => {
  // if (detail.isFree == 1) {
  //   listData.value = []
  //   addArea(true)
  // }
  return detail.isFree == 1
})
//处理省市区数据
const toArrStr = arr => {
  if (isEmpty(arr) || arr.length === 0) {
    return ''
  }
  let arrLen = arr.length
  let row = '['
  for (let i = 0; i < arrLen; i++) {
    row += '['
    for (let j = 0; j < arr[i].length; j++) {
      row += "'" + arr[i][j] + "'"
      if (j < arr[i].length - 1) {
        row += ','
      }
    }
    row += ']'
    if (i < arrLen - 1) {
      row += ','
    }
  }
  row += ']'
  return row
}
const columns = computed<TableColumnData[]>(() => {
  const titles = [
    ['首件(个)', '运费(元)', '续件(个)', '续费(元)'],
    ['首重(kg)', '运费(元)', '续重(kg)', '续费(元)'],
    ['首体积(m³)', '运费(元)', '续体积(m³)', '续费(元)'],
  ]
  return [
    {
      title: '配送区域',
      dataIndex: 'cityArr',
      align: 'center',
      width: 300,
      slotName: 'cityArr',
    },
    {
      title: titles[detail.chargeType][0],
      dataIndex: 'firstPiece',
      align: 'center',
      slotName: 'firstPiece',
      width: 200,
    },
    {
      title: titles[detail.chargeType][1],
      dataIndex: 'firstFee',
      align: 'center',
      width: 200,
      slotName: 'firstFee',
    },

    {
      title: titles[detail.chargeType][2],
      dataIndex: 'continuousPiece',
      align: 'center',
      width: 200,
      slotName: 'continuousPiece',
    },
    {
      title: titles[detail.chargeType][3],
      dataIndex: 'continuousFee',
      align: 'center',
      width: 200,
      slotName: 'continuousFee',
    },

    {
      title: '操作',
      dataIndex: 'op',
      align: 'center',
      slotName: 'op',
      width: 80,
      fixed: 'right',
    },
  ]
})
</script>
<template>
  <CModal v-model:visible="props.show" @before-ok="submit" :mask-closable="false" width="1000px" :title="props.id ? '编辑' : '新建'" @cancel="emit('update:show', false)">
    <div class="content">
      <a-form :model="detail" ref="formRef" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 16 }">
        <div class="grid-2">
          <a-form-item label="模板名称" field="name" :rules="[{ required: true, message: '请输入模板名称' }]" :validate-trigger="['change', 'blur']" :wrapper-col-style="{ flex: '0 0 87.7%' }" :label-col-style="{ flex: '0 0 12.3%' }" style="grid-column: 1 / -1">
            <a-input v-model="detail.name" placeholder="请输入模板名称" />
          </a-form-item>
          <a-form-item label="模板类型" field="isFree" :rules="[{ required: true, message: '请输入模板名称' }]" :validate-trigger="['change', 'blur']">
            <a-radio-group type="button" v-model="detail.isFree">
              <a-radio :value="0">买家承担运费</a-radio>
              <a-radio :value="1">卖家包邮</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="收费方式" field="chargeType" :rules="[{ required: true, message: '请选择收费方式' }]" :validate-trigger="['change', 'blur']">
            <a-radio-group type="button" v-model="detail.chargeType">
              <a-radio :value="0">按件数</a-radio>
              <a-radio :value="1">按重量</a-radio>
              <a-radio :value="2">按体积</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item :wrapper-col-style="{ flex: '0 0 87.7%' }" :label-col-style="{ flex: '0 0 12.3%' }" style="grid-column: 1 / -1">
            <a-space direction="vertical" style="width: 100%">
              <a-button type="primary" long @click="addArea()" :disabled="isDisabled">
                <template #icon>
                  <icon-plus />
                </template>
                添加配送区域
              </a-button>
              <a-table :columns="columns" :data="listData" :scroll="{ x: 700 }" :pagination="false">
                <template #cityArr="{ record, rowIndex }">
                  <!-- <span v-if="rowIndex == 0">全国</span>
                  <a-cascader v-else :options="tree" path-mode v-model="record.cityArr" allow-clear :max-tag-count="1" :field-names="{ label: 'title', value: 'title' }" placeholder="请选择配送区域" multiple /> -->
                  <a-cascader :options="tree" path-mode v-model="record.cityArr" allow-clear :max-tag-count="1" :field-names="{ label: 'title', value: 'title' }" placeholder="请选择配送区域" multiple />
                </template>
                <template #continuousFee="{ record }">
                  <a-input-number :min="0" v-model="record.continuousFee" placeholder="请输入" />
                </template>
                <template #continuousPiece="{ record }">
                  <a-input-number :min="0" v-model="record.continuousPiece" placeholder="请输入" />
                </template>
                <template #firstPiece="{ record }">
                  <a-input-number :min="0" v-model="record.firstPiece" placeholder="请输入" />
                </template>
                <template #firstFee="{ record }">
                  <a-input-number :min="0" v-model="record.firstFee" placeholder="请输入" />
                </template>
                <template #op="{ record, rowIndex }">
                  <a-button type="text" size="small" :disabled="!rowIndex" @click="listData.splice(rowIndex, 1)">删除</a-button>
                </template>
              </a-table>
            </a-space>
          </a-form-item>
        </div>
      </a-form>
    </div>
  </CModal>
</template>
<style lang="less" scoped></style>
